﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebHoiChoMuaBan.Models;
using System.Web.Mvc;
using System.Text;
using WebHoiChoMuaBan.Controllers.Global;

namespace WebHoiChoMuaBan.Controllers.Helpers
{
    public class AdvertHelper : HelperBase
    {
        public struct AdResult
        {
            public int id;
            public string title;
            public decimal? price;
            public string thumb;
            public string content;
            public DateTime postDate;
            public string link;
            public Member member;
            public int? status;
        }

        public struct FetchAdvertisementResult
        {
            public List<Advertisment> advertisement;
            public int totalPages;
        }

        private int memberId;
        private MemberHelper memberHelper;

        public int MemberId
        {
            get { return memberId; }
            set { memberId = value; }
        }

        public AdvertHelper()
        {
            this.memberId = 0;
            this.memberHelper = null;
        }

        public AdvertHelper(int memberId)
            : base()
        {
            this.memberId = memberId;
            this.memberHelper = null;
        }

        public AdvertHelper(MemberHelper hMem)
            : base()
        {
            this.memberHelper = hMem;
        }

  

        public FetchAdvertisementResult getAllListAdvertisement(int pageNum, int numAdvertOnPage)
        {
            IEnumerable<AdResult> advertisement = null;
            advertisement = from m in this.dataContext.Advertisments
                            orderby m.AdPostDate descending
                            select new AdResult
                            {
                                id = m.AdId,
                                title = m.AdTitle,
                                price = m.AdPrice,
                                thumb = m.AdThumb,
                                content = m.AdContent,
                                postDate = m.AdPostDate,
                                link = m.AdLink,
                                member = m.Member,
                                status = m.AdState,
                            };
            return CreateListAdvertisement(pageNum, numAdvertOnPage, advertisement);
        }

        private FetchAdvertisementResult CreateListAdvertisement(int page, int rowPerPage, IEnumerable<AdResult> newAdvertisement)
        {
            List<AdResult> pagedNewAdvertisement = newAdvertisement.Skip((page - 1) * rowPerPage).Take(rowPerPage).ToList();

            int totalPages = (int)Math.Ceiling((double)newAdvertisement.Count() / rowPerPage);

            List<Advertisment> lstNews = new List<Advertisment>(totalPages);
            Advertisment advertisement;
            foreach (var i in pagedNewAdvertisement)
            {
                advertisement = new Advertisment();
                advertisement.AdId = i.id;
                advertisement.AdTitle = i.title;
                advertisement.AdPostDate = i.postDate;
                advertisement.AdPrice = i.price;
                advertisement.AdThumb = i.thumb;
                advertisement.AdContent = i.content;
                advertisement.AdLink = i.link;
                advertisement.Member = i.member;
                advertisement.AdState = i.status;

                //if (i.thumb != null)
                //{
                //    advertisement.NewsProductThumbs = new EntitySet<NewsProductThumb>();
                //    NewsProductThumb thumb = new NewsProductThumb();
                //    thumb.NProThumbName = i.thumbs.NProThumbName;
                //    news.NewsProductThumbs.Add(thumb);
                //}
                //else
                //{
                //    news.NewsProductThumbs = null;
                //}
                //news.MemId = this.memberId;
                lstNews.Add(advertisement);
            }
            FetchAdvertisementResult result;
            result.totalPages = totalPages;
            result.advertisement = lstNews;
            return result;
        }
        public List<Advertisment> getAdsbyMemId(int MemId)
        {
            return (from e in this.dataContext.Advertisments where (e.MemId == MemId && e.AdState == 1) orderby e.AdUpCount descending select e).Take(5).ToList<Advertisment>();
        }

        public void changeAdsStatus(int id)
        {
            Advertisment ad = getAdvertById(id);
            if (ad.AdState == 1)
                ad.AdState = 0;
            else
                ad.AdState = 1;
            Save();

        }

        public Advertisment getAdvertById(int advertId)
        {
            return this.dataContext.Advertisments.SingleOrDefault(n => n.AdId == advertId);
        }

        public List<Advertisment> getHotAd(int page, int rowPerPage)
        {
            IEnumerable<AdResult> hotNews = null;

            hotNews = from a in this.dataContext.Advertisments
                      orderby a.AdUpTime descending
                      select new AdResult
                      {
                          id = a.AdId,
                          title = a.AdTitle,
                          thumb = a.AdThumb,
                          price = a.AdPrice,
                          link = a.AdLink,
                          content = a.AdContent,
                      };

            return CreateListAd(page, rowPerPage, hotNews);
        }

        private List<Advertisment> CreateListAd(int page, int rowPerPage, IEnumerable<AdResult> Ads)
        {
            List<AdResult> pagedAds = Ads.Skip((page - 1) * rowPerPage).Take(rowPerPage).ToList();

            int totalPages = (int)Math.Ceiling((double)Ads.Count() / rowPerPage);

            List<Advertisment> lstAds = new List<Advertisment>(totalPages);
            Advertisment news;
            foreach (var i in pagedAds)
            {
                news = new Advertisment();
                news.AdId = i.id;
                news.AdTitle = i.title;
                news.AdPrice = i.price;
                news.AdThumb = i.thumb;
                news.AdLink = i.link;
                news.AdContent = i.content;
                lstAds.Add(news);
            }
            return lstAds;
        }

        //public Queue<BannerAd> getAdBanners(int countRight)
        //{

        //    var query = (from b in this.dataContext.BannerAds where (b.BannerStartDate > DateTime.Now || b.BannerEndDate < DateTime.Now) select b);

        //    foreach (BannerAd ad in query)
        //    {
        //        ad.BannerStatus = false;
        //    }

        //    Save();


        //    var bannersLeft1 = (from b in this.dataContext.BannerAds
        //              where b.BannerStatus == true && b.BannerPosition == 1
        //              orderby b.BannerPosition descending
        //              select b).Take(1);

        //    var bannersLeft2 = (from b in this.dataContext.BannerAds
        //                        where b.BannerStatus == true && b.BannerPosition == 2
        //                        orderby b.BannerPosition descending
        //                        select b).Take(1);

        //    var bannersLeft3 = (from b in this.dataContext.BannerAds
        //                        where b.BannerStatus == true && b.BannerPosition == 3
        //                        orderby b.BannerPosition descending
        //                        select b).Take(1);

        //    var bannersRight4 = (from b in this.dataContext.BannerAds
        //                                  where b.BannerStatus == true && b.BannerPosition == 4
        //                                  orderby b.BannerPosition descending
        //                                  select b).Take(countRight);

        //    var bannersRight5 = (from b in this.dataContext.BannerAds
        //                                    where b.BannerStatus == true && b.BannerPosition == 5
        //                                    orderby b.BannerPosition descending
        //                                    select b).Take(countRight);

        //    var bannersRight6 = (from b in this.dataContext.BannerAds
        //                         where b.BannerStatus == true && b.BannerPosition == 6
        //                         orderby b.BannerPosition descending
        //                         select b).Take(countRight);
        //    var bannersRight7 = (from b in this.dataContext.BannerAds
        //                         where b.BannerStatus == true && b.BannerPosition == 7
        //                         orderby b.BannerPosition descending
        //                         select b).Take(countRight);
        //    var bannersRight8 = (from b in this.dataContext.BannerAds
        //                         where b.BannerStatus == true && b.BannerPosition == 8
        //                         orderby b.BannerPosition descending
        //                         select b).Take(countRight);

        //    List<BannerAd> banners = bannersLeft1.Union(
        //                                bannersLeft2.Union(
        //                                    bannersLeft3.Union(
        //                                        bannersRight4.Union(
        //                                            bannersRight5.Union(bannersRight6.Union(bannersRight7.Union(bannersRight8)))
        //                                        )
        //                                    )
        //                                )
        //                             ).ToList();

        //    Queue<BannerAd> skBanners = new Queue<BannerAd>(banners.Count);
        //    foreach (BannerAd ban in banners)
        //        skBanners.Enqueue(ban);

        //    return skBanners;
        //}

        public Queue<BannerAd> getAdBanners(int? pageId, int? catId, int countRight)
        {

            //check Date
            var query = (from b in this.dataContext.BannerAds where (b.BannerStartDate > DateTime.Now || b.BannerEndDate < DateTime.Now) select b);

            foreach (BannerAd ad in query)
            {
                ad.BannerStatus = false;
            }

            Save();

            //get by specific page and cate

            #region Home
            if (pageId == null && catId == null)//is Home
            {
                var bannersLeft1 = (from b in this.dataContext.BannerAds
                                    where b.BannerStatus == true && b.BannerPosition == 1 && b.BannerisShowHome == 1
                                    orderby b.BannerPosition descending
                                    select b).Take(1);

                var bannersLeft2 = (from b in this.dataContext.BannerAds
                                    where b.BannerStatus == true && b.BannerPosition == 2 && b.BannerisShowHome == 1
                                    orderby b.BannerPosition descending
                                    select b).Take(1);

                var bannersLeft3 = (from b in this.dataContext.BannerAds
                                    where b.BannerStatus == true && b.BannerPosition == 3 && b.BannerisShowHome == 1
                                    orderby b.BannerPosition descending
                                    select b).Take(1);

                var bannersRight4 = (from b in this.dataContext.BannerAds
                                     where b.BannerStatus == true && b.BannerPosition == 4 && b.BannerisShowHome == 1
                                     orderby b.BannerPosition descending
                                     select b).Take(countRight);

                var bannersRight5 = (from b in this.dataContext.BannerAds
                                     where b.BannerStatus == true && b.BannerPosition == 5 && b.BannerisShowHome == 1
                                     orderby b.BannerPosition descending
                                     select b).Take(countRight);

                var bannersRight6 = (from b in this.dataContext.BannerAds
                                     where b.BannerStatus == true && b.BannerPosition == 6 && b.BannerisShowHome == 1
                                     orderby b.BannerPosition descending
                                     select b).Take(countRight);
                var bannersRight7 = (from b in this.dataContext.BannerAds
                                     where b.BannerStatus == true && b.BannerPosition == 7 && b.BannerisShowHome == 1
                                     orderby b.BannerPosition descending
                                     select b).Take(countRight);
                var bannersRight8 = (from b in this.dataContext.BannerAds
                                     where b.BannerStatus == true && b.BannerPosition == 8 && b.BannerisShowHome == 1
                                     orderby b.BannerPosition descending
                                     select b).Take(countRight);

                List<BannerAd> banners = bannersLeft1.Union(
                                                           bannersLeft2.Union(
                                                               bannersLeft3.Union(
                                                                   bannersRight4.Union(
                                                                       bannersRight5.Union(bannersRight6.Union(bannersRight7.Union(bannersRight8)))
                                                                   )
                                                               )
                                                           )
                                                        ).ToList();

                Queue<BannerAd> skBanners = new Queue<BannerAd>(banners.Count);
                foreach (BannerAd ban in banners)
                    skBanners.Enqueue(ban);

                return skBanners;
            }

            #endregion

            #region pageHome
            if (pageId != null && catId == 0) //trang page Home
            {
                var bannersLeft1 = (from b in this.dataContext.BannerAds
                                    where b.BannerStatus == true && b.BannerPosition == 1 && b.BannerPageId == pageId
                                    orderby b.BannerPosition descending
                                    select b).Take(1);

                var bannersLeft2 = (from b in this.dataContext.BannerAds
                                    where b.BannerStatus == true && b.BannerPosition == 2 && b.BannerPageId == pageId
                                    orderby b.BannerPosition descending
                                    select b).Take(1);

                var bannersLeft3 = (from b in this.dataContext.BannerAds
                                    where b.BannerStatus == true && b.BannerPosition == 3 && b.BannerPageId == pageId
                                    orderby b.BannerPosition descending
                                    select b).Take(1);

                var bannersRight4 = (from b in this.dataContext.BannerAds
                                     where b.BannerStatus == true && b.BannerPosition == 4 && b.BannerPageId == pageId
                                     orderby b.BannerPosition descending
                                     select b).Take(countRight);

                var bannersRight5 = (from b in this.dataContext.BannerAds
                                     where b.BannerStatus == true && b.BannerPosition == 5 && b.BannerPageId == pageId
                                     orderby b.BannerPosition descending
                                     select b).Take(countRight);

                var bannersRight6 = (from b in this.dataContext.BannerAds
                                     where b.BannerStatus == true && b.BannerPosition == 6 && b.BannerPageId == pageId
                                     orderby b.BannerPosition descending
                                     select b).Take(countRight);
                var bannersRight7 = (from b in this.dataContext.BannerAds
                                     where b.BannerStatus == true && b.BannerPosition == 7 && b.BannerPageId == pageId
                                     orderby b.BannerPosition descending
                                     select b).Take(countRight);
                var bannersRight8 = (from b in this.dataContext.BannerAds
                                     where b.BannerStatus == true && b.BannerPosition == 8 && b.BannerPageId == pageId
                                     orderby b.BannerPosition descending
                                     select b).Take(countRight);

                List<BannerAd> banners = bannersLeft1.Union(
                                                           bannersLeft2.Union(
                                                               bannersLeft3.Union(
                                                                   bannersRight4.Union(
                                                                       bannersRight5.Union(bannersRight6.Union(bannersRight7.Union(bannersRight8)))
                                                                   )
                                                               )
                                                           )
                                                        ).ToList();




                Queue<BannerAd> skBanners = new Queue<BannerAd>(banners.Count);
                foreach (BannerAd ban in banners)
                    skBanners.Enqueue(ban);

                return skBanners;
            }
            #endregion

            #region Cate
            if (pageId != null && catId != 0)//là trang danh mục con
            {

                BannerAd ba = (from e in this.dataContext.BannerAds where e.BannerPosition == 1 select e).SingleOrDefault();
                string[] arr = ba.BannerCategoryList.Split(';');
                List<int?> bannerCate = new List<int?>();
                bannerCate.Clear();
                foreach (string tmp in arr)
                {
                    try
                    {
                        bannerCate.Add((int?)int.Parse(tmp));
                    }
                    catch
                    {
                    }
                }

                var bannersLeft1 = (from b in this.dataContext.BannerAds
                                    where b.BannerStatus == true && b.BannerPosition == 1 && bannerCate.Contains(catId)
                                    orderby b.BannerPosition descending
                                    select b).Take(1);

                BannerAd ba2 = (from e in this.dataContext.BannerAds where e.BannerPosition == 2 select e).SingleOrDefault();
                string[] arr2 = ba2.BannerCategoryList.Split(';');
                List<int?> bannerCate2 = new List<int?>();
                bannerCate2.Clear();
                foreach (string tmp in arr2)
                {
                    try
                    {
                        bannerCate2.Add((int?)int.Parse(tmp));
                    }
                    catch
                    {
                    }
                }


                var bannersLeft2 = (from b in this.dataContext.BannerAds
                                    where b.BannerStatus == true && b.BannerPosition == 2 && bannerCate2.Contains(catId)
                                    orderby b.BannerPosition descending
                                    select b).Take(1);


                BannerAd ba3 = (from e in this.dataContext.BannerAds where e.BannerPosition == 3 select e).SingleOrDefault();
                string[] arr3 = ba3.BannerCategoryList.Split(';');
                List<int?> bannerCate3 = new List<int?>();
                bannerCate3.Clear();
                foreach (string tmp in arr3)
                {
                    try
                    {
                        bannerCate3.Add((int?)int.Parse(tmp));
                    }
                    catch
                    {
                    }
                }
                var bannersLeft3 = (from b in this.dataContext.BannerAds
                                    where b.BannerStatus == true && b.BannerPosition == 3 && bannerCate3.Contains(catId)
                                    orderby b.BannerPosition descending
                                    select b).Take(1);

                BannerAd ba4 = (from e in this.dataContext.BannerAds where e.BannerPosition == 4 select e).SingleOrDefault();
                string[] arr4 = ba4.BannerCategoryList.Split(';');
                List<int?> bannerCate4 = new List<int?>();
                bannerCate4.Clear();
                foreach (string tmp in arr4)
                {
                    try
                    {
                        bannerCate4.Add((int?)int.Parse(tmp));
                    }
                    catch
                    {
                    }
                }

                var bannersRight4 = (from b in this.dataContext.BannerAds
                                     where b.BannerStatus == true && b.BannerPosition == 4 && bannerCate4.Contains(catId)
                                     orderby b.BannerPosition descending
                                     select b).Take(countRight);

                BannerAd ba5 = (from e in this.dataContext.BannerAds where e.BannerPosition == 5 select e).SingleOrDefault();
                string[] arr5 = ba5.BannerCategoryList.Split(';');
                List<int?> bannerCate5 = new List<int?>();
                bannerCate5.Clear();
                foreach (string tmp in arr5)
                {
                    try
                    {
                        bannerCate5.Add((int?)int.Parse(tmp));
                    }
                    catch
                    {
                    }
                }
                var bannersRight5 = (from b in this.dataContext.BannerAds
                                     where b.BannerStatus == true && b.BannerPosition == 5 && bannerCate5.Contains(catId)
                                     orderby b.BannerPosition descending
                                     select b).Take(countRight);

                BannerAd ba6 = (from e in this.dataContext.BannerAds where e.BannerPosition == 6 select e).SingleOrDefault();
                string[] arr6 = ba6.BannerCategoryList.Split(';');
                List<int?> bannerCate6 = new List<int?>();
                bannerCate6.Clear();
                foreach (string tmp in arr6)
                {
                    try
                    {
                        bannerCate6.Add((int?)int.Parse(tmp));
                    }
                    catch
                    {
                    }
                }
                var bannersRight6 = (from b in this.dataContext.BannerAds
                                     where b.BannerStatus == true && b.BannerPosition == 6 && bannerCate6.Contains(catId)
                                     orderby b.BannerPosition descending
                                     select b).Take(countRight);

                BannerAd ba7 = (from e in this.dataContext.BannerAds where e.BannerPosition == 7 select e).SingleOrDefault();
                string[] arr7 = ba7.BannerCategoryList.Split(';');
                List<int?> bannerCate7 = new List<int?>();
                bannerCate7.Clear();
                foreach (string tmp in arr7)
                {
                    try
                    {
                        bannerCate7.Add((int?)int.Parse(tmp));
                    }
                    catch
                    {
                    }
                }

                var bannersRight7 = (from b in this.dataContext.BannerAds
                                     where b.BannerStatus == true && b.BannerPosition == 7 && bannerCate7.Contains(catId)
                                     orderby b.BannerPosition descending
                                     select b).Take(countRight);

                BannerAd ba8 = (from e in this.dataContext.BannerAds where e.BannerPosition == 8 select e).SingleOrDefault();
                string[] arr8 = ba8.BannerCategoryList.Split(';');
                List<int?> bannerCate8 = new List<int?>();
                bannerCate8.Clear();
                foreach (string tmp in arr8)
                {
                    try
                    {
                        bannerCate8.Add((int?)int.Parse(tmp));
                    }
                    catch
                    {
                    }
                }
                var bannersRight8 = (from b in this.dataContext.BannerAds
                                     where b.BannerStatus == true && b.BannerPosition == 8 && bannerCate8.Contains(catId)
                                     orderby b.BannerPosition descending
                                     select b).Take(countRight);

                List<BannerAd> banners = bannersLeft1.Union(
                                                           bannersLeft2.Union(
                                                               bannersLeft3.Union(
                                                                   bannersRight4.Union(
                                                                       bannersRight5.Union(bannersRight6.Union(bannersRight7.Union(bannersRight8)))
                                                                   )
                                                               )
                                                           )
                                                        ).ToList();

                Queue<BannerAd> skBanners = new Queue<BannerAd>(banners.Count);
                foreach (BannerAd ban in banners)
                    skBanners.Enqueue(ban);

                return skBanners;
            }
            #endregion
            return null;
        }

        public string showBanner(ViewDataDictionary ViewData, int position)
        {
            int width;
            string defaultImg;
            Queue<BannerAd> banners = (Queue<BannerAd>)ViewData["BannerAd"];
            StringBuilder sb = new StringBuilder();
            if (position <= 3)
            {
                width = 0x2db;
                defaultImg = "banner_center_bottom.png";
            }
            else if (position <= 7)
            {
                width = 0xef;
                defaultImg = "hoicho_bannerad_right.gif";
            }
            else
            {
                width = 0x145;
                defaultImg = "hoicho_ad_bottom.gif";
            }
            BannerAd banner = null;
            int i = 1;
            int c = 0;
            bool found = false;
            if (banners != null)
            {
                c = banners.Count;
            }
            while (i <= c)
            {
                banner = banners.Dequeue();
                if (banner.BannerPosition == position)
                {
                    found = true;
                    if (banner.BannerType.Equals("image"))
                    {
                        sb.Append(string.Format("<a href='{0}'><img alt='{1}' src='{2}' width='{3}' height='{4}' /></a>", new object[] { banner.BannerLink, banner.BannerText, banner.BannerImg, width, 0xeb }));
                    }
                    else if (banner.BannerType.Equals("flash"))
                    {
                        sb.Append(string.Format(" <a href='{0}'><object type='application/x-shockwave-flash'  data='{1}' width='{2}' height='{3}'>", new object[] { banner.BannerLink, banner.BannerImg, width, 0xeb }));
                        sb.Append(string.Format(" <param name='movie' value='{0}' />", banner.BannerImg));
                        sb.Append(string.Format("<param name='quality' value='high'/>   <param name='wmode' value='transparent'/></object></a>", new object[0]));
                    }
                    else
                    {
                        sb.Append("<div id= 'container' >Loading the player ...</div>  ");
                        sb.Append("<script  type= 'text/javascript'>  ");
                        sb.Append("jwplayer ( 'container' ).setup({ ");
                        sb.Append("autostart:true,");
                        sb.Append("repeat:true,");
                        sb.Append("controlbar:'none' , ");
                        sb.Append("flashplayer :'../../Content/players/player.swf',  ");
                        sb.Append(string.Format("file:   '{0}', ", banner.BannerImg));
                        sb.Append("height :235,");
                        sb.Append("width:" + width);
                        sb.Append("});  ");
                        sb.Append("</script>");
                    }
                }
                else
                {
                    banners.Enqueue(banner);
                }
                i++;
            }
            ViewData["BannerAd"] = banners;
            if (!found)
            {
                return string.Format("<a href='#'><img src='../Content/Images/{0}' alt='' width='{1}' /></a>", defaultImg, width);
            }
            return sb.ToString();
        }

        public FetchAdvertisementResult getListAdvertisement(int pageNum)
        {
            IEnumerable<AdResult> advertisement = null;
            if (this.memberId > 0)
            {
                advertisement = from m in base.dataContext.Advertisments
                                where m.MemId == this.memberId
                                orderby m.AdPostDate descending
                                select new AdResult { id = m.AdId, title = m.AdTitle, price = m.AdPrice, thumb = m.AdThumb, content = m.AdContent, postDate = m.AdPostDate, link = m.AdLink, status = m.AdState };
            }
            return this.CreateListAdvertisement(pageNum, 6, advertisement);
        }

        //
        // Insert/Delete Methods
        public void Add(Advertisment advertisement)
        {
            this.dataContext.Advertisments.InsertOnSubmit(advertisement);
        }

        //Delete Methods
        public void Delete(Advertisment advertisement)
        {
            this.dataContext.Advertisments.DeleteOnSubmit(advertisement);
        }

        //
        // Persistence
        public void Save()
        {
            this.dataContext.SubmitChanges();
        }
    }
}